import { TextWidget } from '@inbiz/react';
import { Empty, Spin } from 'antd';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import AppList from '../../../FunPermission/components/Permission/List';
import TreeList from '../../../FunPermission/components/Permission/Tree';
import { addMenuUserPerm, delMenuUserPerm, getMenuUserPerm } from '../../../service';
import '../../../style.less';

function Menu(props: any) {
  const { appList, selectMember, permConfig, containerHeight } = props;
  const { MemberId, MemberType } = selectMember;
  const [outId, $outId] = useState(appList[0]?.OutId); // 应用Id
  const [selectedTreeKeys, $selectedTreeKeys] = useState([]); // 菜单Id
  const [permList, $permList] = useState([]); //菜单权限
  const [menuList, $menuList] = useState([]); //菜单
  const [loadding1, $loadding1] = useState(false); //菜单加载

  // 站点点击，获取对应的菜单
  useEffect(() => {
    if (outId) {
      $permList([]);
      $menuList([]);
      getMenuUserPermFun();
    }
  }, [outId, MemberId]);

  // 获取菜单列表
  const getMenuUserPermFun = () => {
    $loadding1(true);
    if (MemberId) {
      const payload = {
        siteOutId: outId,
        parentId: '',
        memberType: MemberType,
        memberId: MemberId,
      };
      getMenuUserPerm(payload).then((res) => {
        $loadding1(false);
        if (!res) return;
        res.forEach((item: any) => {
          item.selectable = false;
          item.children = formateChildren(item.Children);
        });
        $menuList((origin) => {
          return [...res];
        });
        $permList((origin) => {
          return [...getRultPerm(res)];
        });
      });
    }
  };
  const getRultPerm = (res) => {
    let newPermList = [];
    res.forEach((item) => {
      if (item.PermissionValue != 0) {
        newPermList.push(item.OutId);
      }
      if (item.Children?.length) {
        newPermList = [...newPermList, ...getRultPerm(item.Children)];
      }
    });
    return newPermList;
  };

  const formateChildren = (children) => {
    children?.length &&
      children.forEach((item: any) => {
        if (item.Children?.length) {
          item.children = formateChildren(item.Children);
        }
      });
    return children;
  };

  const appClick = (outId: number) => {
    $outId(outId);
  };

  // 异步加载菜单
  const onLoadData = (treeNode: any) => {
    return new Promise((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      const payload = {
        siteOutId: outId,
        parentId: treeNode.props.dataRef.OutId,
        memberType: MemberType,
        memberId: MemberId,
      };
      getMenuUserPerm(payload).then((res) => {
        treeNode.props.dataRef.children = res;
        $menuList(updateTreeData(menuList, res, treeNode.props.eventKey));
        let newPermList: any[] = [];
        res.forEach((item: any) => {
          item.selectable = false;
          if (item.PermissionValue != 0) {
            newPermList.push(item.OutId);
          }
        });
        $permList((origin) => {
          return [...origin, ...newPermList];
        });
        resolve();
      });
    });
  };

  const updateTreeData = (list, children, key) => {
    return list.map((node) => {
      if (node.OutId === key) {
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData(node.children, key, children),
        };
      }
      return node;
    });
  };
  // 查找所有子节点key
  const findAllchildrenkeys = (node) => {
    let children = [];
    node.children?.forEach((item1: any) => {
      children.push(item1.key);
      if (item1.children?.length) {
        children = [...children, ...findAllchildrenkeys(item1)];
      }
    });
    return children;
  };
  // 查找所有父节点key
  const findAllparentKeys = (list, key) => {
    for (let i in list) {
      if (list[i].OutId === key) {
        //查询到返回该数组对象
        return [];
      }
      if (list[i].children) {
        let node = findAllparentKeys(list[i].children, key);
        if (node !== undefined) {
          //查询到把父节点连起来
          return node.concat(list[i].OutId);
        }
      }
    }
  };

  const onCheck = (checkedKeys, e) => {
    let childrenKeys = findAllchildrenkeys(e.node) || [];
    let parentKeys = findAllparentKeys(menuList, e.node.props.eventKey) || [];
    if (e.checked) {
      // 添加权限
      changePerm(
        'add',
        [...checkedKeys.checked, ...childrenKeys, ...parentKeys],
        checkedKeys.checked,
      );
    } else {
      //删除权限
      let newcheckedKeys = [];
      checkedKeys.checked?.map((item) => {
        if (childrenKeys.indexOf(item) == -1) {
          newcheckedKeys.push(item);
        }
      });
      changePerm('del', newcheckedKeys, checkedKeys.checked);
    }
  };
  const changePerm = (type, checkedKeys, nowChkedKeys) => {
    let payload = {
      siteOutId: outId,
      memberType: MemberType,
      memberId: MemberId,
    };
    let menuFuncPermList = [];
    if (type == 'add') {
      checkedKeys.forEach((item) => {
        if (permList.indexOf(item) == -1)
          menuFuncPermList.push({
            menuOutId: item,
            permissionValue: 4,
          });
      });
      payload.menuFuncPermList = menuFuncPermList;
    } else {
      permList.forEach((item) => {
        if (checkedKeys.indexOf(item) == -1) menuFuncPermList.push(item);
      });
      payload.permissionIds = findpremIds(menuFuncPermList, menuList);
    }
    // dispatch({
    //   type: type == 'add' ? 'permissionFun/addMenuUserPerm' : 'permissionFun/delMenuUserPerm',
    //   payload,
    // }).then(res => {
    //   getMenuUserPermFun();
    //   // const oldPerm = permList;
    //   // $permList(origin => {
    //   //   return [...checkedKeys]
    //   // })
    //   // if (!res) {
    //   //   $permList(origin => {
    //   //     return [...oldPerm]
    //   //   })
    //   // }
    // })
    permRequest(type == 'add' ? addMenuUserPerm : delMenuUserPerm, payload);
  };

  const permRequest = (service: any, paylaod: object) => {
    service(paylaod).then((res: any) => {
      if (!res) {
        return;
      }
      getMenuUserPermFun();
    });
  };
  // 通过outId查找对应权限值
  const findpremIds = (outIds, list) => {
    let temp = [];
    list.forEach((menu) => {
      outIds.forEach((outId) => {
        if (menu.OutId == outId) {
          temp.push(menu.PermissionId);
        }
      });
      if (menu.children?.length) {
        temp = [...temp, ...findpremIds(outIds, menu.children)];
      }
    });
    return temp;
  };

  // 判断是否是ifream嵌套
  const isIframe = useMemo(() => {
    return location?.hash?.indexOf('permissionFun') != -1;
  }, []);

  return (
    <div className={'main'} style={{ height: `calc(${containerHeight} - 144px)` }}>
      <div className={'appList'}>
        <AppList outId={outId} appClick={appClick} list={appList} />
      </div>
      <div className={'lastTreeList'}>
        {menuList.length ? (
          <TreeList
            key={MemberId}
            list={menuList}
            // onLoadData={onLoadData}
            selectedKeys={selectedTreeKeys}
            treeClick={(arr) => $selectedTreeKeys(arr)}
            checkable={true}
            checkedKeys={permList}
            checkStrictly={true}
            treeCheck={onCheck}
          />
        ) : loadding1 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>
    </div>
  );
}

export default Menu;
